package com.laolu.icon.utils;

import com.laolu.icon.entity.IconInfo;
import com.laolu.icon.exception.MyException;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef.HWND;
import com.sun.jna.platform.win32.WinDef.LPARAM;
import com.sun.jna.platform.win32.WinDef.LRESULT;
import com.sun.jna.platform.win32.WinDef.WPARAM;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

import static com.laolu.icon.constants.LVM_ListViewMessage.LVM_SETITEMPOSITION;

@Slf4j
public class MyIcon {
	
	/**
	 * 获取桌面图标信息
	 * @return
	 */
	public List<IconInfo> getDesktopIconInfo() throws MyException {
		MyDesktop myDesktop = new MyDesktop();
		ShortcutUtils shortcutUtils = new ShortcutUtils();
		return getDesktopIconInfo(myDesktop, shortcutUtils);
		
	}
	
	public List<IconInfo> getDesktopIconInfo(MyDesktop myDesktop, ShortcutUtils shortcutUtils) throws MyException {
		List<String> matchedFileList = new LinkedList<>();
		//创建相关工具类
		MyFile myFile = new MyFile();
		
		//获取桌面图标位置信息
		List<IconInfo> list = myDesktop.getDesktopIconRect();
		//获取桌面文件列表
		List<String> desktopFileList = myFile.getDesktopFileList();
		for (IconInfo iconInfo : list) {
			//获取图标标题
			String iconTitle = iconInfo.getTitle();
			//获取图标对应的文件路径
			String filePath = desktopFileList.stream()
					.filter(e -> !matchedFileList.contains(e)
							&& (e.toLowerCase().endsWith(File.separator + iconTitle.toLowerCase())
							|| e.toLowerCase().endsWith(File.separator + iconTitle.toLowerCase() + ".lnk")))
					.limit(1)
					.collect(Collectors.joining());
			
			if (!filePath.isEmpty()) {
				matchedFileList.add(filePath);
				iconInfo.setFullName(filePath);
				//设置文件类型
				File file = new File(filePath);
				if (file.isFile()) {
					iconInfo.setType(IconInfo.ShortcutType.File);
					//判断是否.lnk结尾的快捷方式
					if (filePath.endsWith(".lnk")) {
						iconInfo.setType(IconInfo.ShortcutType.Shortcut);
						//获取快捷方式信息
						iconInfo = shortcutUtils.getShortcutInfo(iconInfo);
					}
				} else if (file.isDirectory()) {
					iconInfo.setType(IconInfo.ShortcutType.Folder);
				}
			} else {
				//是[此电脑][回收站]此类图标
				iconInfo.setType(IconInfo.ShortcutType.SymbolicLink);
			}
		}
		return list;
	}
	
	
	/**
	 * 设置图标位置
	 * @param index
	 * 		图标索引
	 * @param left
	 * 		图标距离屏幕左侧距离
	 * @param top
	 * 		图标距离屏幕顶部距离
	 * @param isAbsolute
	 * 		是否绝对位置，如果不是绝对位置，位置被占据时会占据下一个图标位置
	 */
	public LRESULT setIconPosition(HWND hDeskWnd, int index, int left, int top, boolean isAbsolute) {
		if (isAbsolute) {
			top -= 5;
		}
		int position = top << 16 | left;
		return User32.INSTANCE.SendMessage
				(hDeskWnd, LVM_SETITEMPOSITION, new WPARAM(index), new LPARAM(position));
	}
	
	
}
